package com.aiti.lulian.service.impl;

import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.crm.CrmListFieldConfigDto;
import com.aiti.lulian.entity.SysData;
import com.aiti.lulian.entity.crm.CrmListFieldConfig;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CrmListFieldConfigMapper;
import com.aiti.lulian.service.ICrmListFieldConfigService;
import com.aiti.lulian.service.ISysDataService;
import com.aiti.lulian.vo.crm.CrmListFieldModuleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CrmListFieldConfigServiceImpl extends BaseSerivceImpl<CrmListFieldConfigMapper, CrmListFieldConfig> implements ICrmListFieldConfigService {

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;

    @Autowired
    private ISysDataService sysDataService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message addOrUpdateListFieldConfig(CrmListFieldConfigDto dto) {
        String userId = dto.getUserId();
        String enterpriseId = dto.getEnterpriseId();
        List<CrmListFieldConfig> configList = dto.getConfigList();
        List<CrmListFieldConfig> existingConfigList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, userId).eq(CrmListFieldConfig::getEnterpriseId, dto.getEnterpriseId()).eq(CrmListFieldConfig::getModule, dto.getModule()));
        if (existingConfigList.size() == 0) {
            //新增
            List<CrmListFieldConfig> insertDataModel = configList.stream().peek(i -> {
                i.setBaseId(null);
                i.setModule(dto.getModule());
                i.setEnterpriseId(enterpriseId);
                i.setCreator(userId);
                i.setBaseCreateTime(new Date());
            }).collect(Collectors.toList());
            this.saveBatch(insertDataModel);
        } else {
            //更新
            List<CrmListFieldConfig> updateDataModel = configList.stream().peek(i -> {
                i.setBaseUpdateTime(new Date());
            }).collect(Collectors.toList());
            this.updateBatchById(updateDataModel);
        }
        return Message.success();
    }

    @Override
    public List<CrmListFieldConfig> getListFieldConfig(String userId, String enterpriseId, String module) {
        List<CrmListFieldConfig> existingConfigList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, userId).eq(CrmListFieldConfig::getEnterpriseId, enterpriseId).eq(CrmListFieldConfig::getModule, module).orderByAsc(CrmListFieldConfig::getSort));
        if (existingConfigList.size() == 0) {
            Message message = cloudShowManagerSubService.getUserIds(userId);
            if (message == null) {
                throw new RuntimeException("获取数据失败");
            } else if (! message.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                throw new RuntimeException("查询数据失败");
            } else {
                List<String> userIds = (List<String>) message.getObj();
                if (userIds == null) {
                    throw new RuntimeException("操作失败");
                }
                if (userIds.size() > 0) {
                    for (String HighPermissionUserId : userIds) {
                        List<CrmListFieldConfig> configList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, HighPermissionUserId).eq(CrmListFieldConfig::getEnterpriseId, enterpriseId).eq(CrmListFieldConfig::getModule, module).orderByAsc(CrmListFieldConfig::getSort));
                        if (configList.size() > 0) {
                            existingConfigList = configList;
                            break;
                        }
                    }
                    if (existingConfigList.size() == 0) {
                        List<CrmListFieldConfig> defaultConfigList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, "1").eq(CrmListFieldConfig::getEnterpriseId, "1").eq(CrmListFieldConfig::getModule, module).orderByAsc(CrmListFieldConfig::getSort));
                        existingConfigList = defaultConfigList;
                    }
                } else {
                    List<CrmListFieldConfig> defaultConfigList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, "1").eq(CrmListFieldConfig::getEnterpriseId, "1").eq(CrmListFieldConfig::getModule, module).orderByAsc(CrmListFieldConfig::getSort));
                    existingConfigList = defaultConfigList;
                }
            }
        }
        return existingConfigList;
    }

    @Override
    public List<CrmListFieldModuleVo> getListConfigurableField(String userId, String enterpriseId, Page<SysData> page) {
        Page<SysData> moduleListPage = sysDataService.page(page, new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CRM_FIELD_CONFIG_MODULE").orderByAsc(SysData::getBaseId));
        List<SysData> moduleList = moduleListPage.getRecords();
        Message message = cloudShowManagerSubService.getUserIds(userId);
        if (message == null) {
            throw new RuntimeException("获取数据失败");
        } else if (! message.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
            throw new RuntimeException("查询数据失败");
        } else {
            List<String> userIds = (List<String>) message.getObj();
            if (userIds == null) {
                throw new RuntimeException("操作失败");
            }
            ArrayList<CrmListFieldModuleVo> resultList = new ArrayList<>();
            for (SysData module : moduleList) {
                String baseId = module.getBaseId();
                List<CrmListFieldConfig> existingConfigList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, userId).eq(CrmListFieldConfig::getEnterpriseId, enterpriseId).eq(CrmListFieldConfig::getModule, baseId).eq(CrmListFieldConfig::getIsShow, "1").orderByAsc(CrmListFieldConfig::getSort));
                if (userIds.size() > 0) {
                    for (String HighPermissionUserId : userIds) {
                        List<CrmListFieldConfig> configList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, HighPermissionUserId).eq(CrmListFieldConfig::getEnterpriseId, enterpriseId).eq(CrmListFieldConfig::getModule, baseId).eq(CrmListFieldConfig::getIsShow, "1").orderByAsc(CrmListFieldConfig::getSort));
                        if (configList.size() > 0) {
                            existingConfigList = configList;
                            break;
                        }
                    }
                    if (existingConfigList.size() == 0) {
                        List<CrmListFieldConfig> defaultConfigList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, "1").eq(CrmListFieldConfig::getEnterpriseId, "1").eq(CrmListFieldConfig::getModule, baseId).orderByAsc(CrmListFieldConfig::getSort));
                        existingConfigList = defaultConfigList;
                    }
                } else {
                    List<CrmListFieldConfig> defaultConfigList = this.list(new LambdaQueryWrapper<CrmListFieldConfig>().eq(CrmListFieldConfig::getCreator, "1").eq(CrmListFieldConfig::getEnterpriseId, "1").eq(CrmListFieldConfig::getModule, baseId).orderByAsc(CrmListFieldConfig::getSort));
                    existingConfigList = defaultConfigList;
                }
                CrmListFieldModuleVo crmListFieldModuleVo = new CrmListFieldModuleVo();
                BeanUtils.copyProperties(module, crmListFieldModuleVo);
                crmListFieldModuleVo.setAllField(existingConfigList.stream().map(CrmListFieldConfig::getFieldNameCh).collect(Collectors.joining(",")));
                resultList.add(crmListFieldModuleVo);
            }
            return resultList;
        }
    }
}
